package utils;

import org.eclipse.jdt.core.dom.*;

import java.util.List;

public class ASTUtils {

	public static void main(String[] args) {
		String sourceCode = " public class Adder {" +
				"           public int add(double a, double b) {" +
				"               double sum = a + b;" + "int a = 1;"+
				"               return sum.intValue();" +
				"           }" +
				"       }";


		// 创建一个 AST 构建器
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(sourceCode.toCharArray());
		parser.setKind(ASTParser.K_COMPILATION_UNIT);

		// 解析源代码并创建 AST
		CompilationUnit cu = (CompilationUnit) parser.createAST(null);

		AST ast = cu.getAST();

		cu.accept(new ASTVisitor() {
			@Override
			public boolean visit(MethodDeclaration node) {
				node.setName(ast.newSimpleName("plus"));
				// 获取方法体并更改其内容

				if (node.getBody() != null) {
					List statements = node.getBody().statements();
					for (Object statement : statements) {
						if(statement instanceof ReturnStatement returnStatement) {

						}
						if(statement instanceof VariableDeclarationStatement vds){
							System.out.println(vds);
							vds.setType(ast.newPrimitiveType(PrimitiveType.INT));
							vds.accept(new ASTVisitor() {
								@Override
								public boolean visit(VariableDeclarationFragment node) {
									System.out.println(node.getLength());
									return true;
								}
							});
						}
					}
				}
				return true; // 继续遍历其他节点（如果有）
			}
		});

		System.out.println( cu.toString() );
	}

	// 创建一个源代码字符串

}
